
/**
 *  用例 :
 *  var hws = new Hws("localhost:8080/hjsp/ws/a/1", function(e,o) {
	  console.log(e)
	})
 */

!function(p, e) { "object" == typeof exports && "undefined" != typeof module ? module.exports = e : "function" == typeof define && define.amd ? define(e) : (p = "undefined" != typeof globalThis ? globalThis : p || self).Hws = e }
	(this, function() {"use strict";
		return function(服务路径, 收到消息回调, 连接成功回调, 断开回调) {
			var that = this;
			that.socket = null;
			that.messageNum = 0;//收到消息数
			that.socketConnectedEnable = true;
			that._onReceiveMsg = 收到消息回调;
			that._onOpen = 连接成功回调;
			that._onClose = 断开回调;


			if (服务路径 == null || 服务路径 == '') return null;

			if (服务路径.startsWith('ws://'))
				this._url = 服务路径;
			else
				this._url = "ws://" + 服务路径;
			//console.log(that._url, serverurl)
			that.connect = function() {
				if ('WebSocket' in window) {
					that.socket = new window.WebSocket(that._url);
				} else {
					if ('MozWebSocket' in window) {
						that.socket = new window.MozWebSocket(that._url);
					} else {
						console.log('当前浏览器 不支持 websocket')
						return;
					}
				}
				//收到消息
				that.socket.onmessage = function(event) {
					that.messageNum++;
					if (that._onReceiveMsg)
						that._onReceiveMsg(event, that);
				};
				//连接成功
				that.socket.onopen = function(event) {
					if (that._onOpen)
						that._onOpen(event);
					console.log("连接开启!")
				};
				//连接成功
				that.socket.onclose = function(event) {
					if (that._onClose)
						that._onClose(event);
					console.log("连接关闭!")
				};
			}
			that.send = function(message) {
				if (that.socket && that.socket.readyState == 1) {
					that.socket.send(message);
				} else {
					that.socket = null;
					console.log("连接已经关闭,重新连接");
					setTimeout(that.connect, 1000);
				}
			}

			//保持连接的方式 每隔100s  ping一下主机 如果断开重连
			that.timer = setInterval(function() {
				if (that.socketConnectedEnable) {
					//console.log("ping");
					that.send("hi");
				}
			}, 180000);
			//
			that.close = function() {
				console.log("关闭??")
				clearTimeout(that.timer);
				that.socket.close();
			};

			that.isSupWs = function() {
				return (window.WebSocket || window.MozWebSocket) ? true : false;
			}
			that.connect();
			return that;
		}
	});